<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" size="small" v-show="showSearch" label-width="68px">
            <el-row>
                <el-card shadow="always" style="margin-bottom: 10px;">
                    <el-radio-group v-model="queryType" size="mini">
                        <el-radio border key="2"  label="2">分公司</el-radio>
                        <el-radio border key="3"  label="3">分区</el-radio>
                        <el-radio border key="4"  label="4">部门归属</el-radio>
                        <el-radio border key="6"  label="6">个人</el-radio>
                    </el-radio-group>
                </el-card>
            </el-row>
            <el-row>
                <el-col :span="6">
                    <el-form-item label="备注时间" prop="goalDate">
                        <el-date-picker v-model="goalDate" type="daterange" :picker-options="pickerOptions"
                            range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd"
                            format="yyyy-MM-dd" align="right" style="width: 100%;">
                        </el-date-picker>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="部门归属" prop="deptId">
                        <treeselect v-model="queryParams.params.deptId" :options="deptOptions" :show-count="true"
                            placeholder="请选择部门归属" :default-expand-level="4" />
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="顾问" prop="empId" >
                        <el-select v-model="queryParams.empId" placeholder="顾问" clearable filterable>
                            <el-option v-for="user in sysUsersList" :key="user.userId" :label="user.nickName"
                                :value="user.userId" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item>
                        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5"></el-col>
        </el-row>

        <el-table v-loading="loading" :data="userGoalList" show-summary :summary-method="getSummaries">
            <template v-if="queryType == 6">
                <el-table-column label="顾问" align="center" prop="nick_name" />
                <el-table-column label="部门归属" align="center" prop="dept_name" />
                <el-table-column label="备注客户数" align="center" prop="custCommentTimes" >
                  <template slot-scope="scope">
                    <span class="report_span1" @click="custleveldataDetails(scope.row.custIds)">{{scope.row.custCommentTimes}}</span>
                  </template>
                </el-table-column>
                <el-table-column label="备注次数" align="center" prop="commentTimes" />
                <el-table-column label="客户平均备注次数" align="center" prop="avgCustCommentCount" />
            </template>
            <template v-else>
                <el-table-column label="部门归属" align="center" prop="dept_name" />
                <el-table-column label="备注客户数" align="center" prop="custCommentTimes" >

                </el-table-column>
                <el-table-column label="人均备注客户数" align="center" prop="avgCustCommentTimes" />
                <el-table-column label="备注次数" align="center" prop="commentTimes" />
                <el-table-column label="人均备注次数" align="center" prop="avgCommentTimes" />
                <el-table-column label="占比" align="center" prop="commentRate" />
                <el-table-column label="客户平均备注次数" align="center" prop="avgCustCommentCount" />
            </template>
        </el-table>
        <!-- 查看客户列表 -->
        <el-dialog :title="title" :visible.sync="open" class="dialogCust" width="96%" :fullscreen="modal" append-to-body :modal="modal" :destroy-on-close="modal">
          <cust-info-list :form.sync="form"></cust-info-list>
        </el-dialog>
    </div>
</template>

<script>
import { getCustCommentStaticslist } from "@/api/crmsys/report/custCommentStatics";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import Treeselect from "@riophae/vue-treeselect";
import { childrenAlldeptTree } from "@/api/system/user";
import { getAllDeptandUsers } from "@/api/crmsys/custinfo/custinfo";
import CustInfoList from "@/components/crmSys/custInfoList.vue";

export default {
    name: "CustCommentStatics",
    components: { Treeselect, CustInfoList},
    data() {
      return {
            open:false,
            modal:false,
            title:'客户列表',
            form:{},//通过form去子组件查询列表数据
            goalDate: null,
            // 周目标管理表格数据
            userGoalList: [],
            // 部门归属树选项
            deptOptions: [],
            sysUsersList: [],
            queryType: "6",
            queryParams: {
                params: {
                }
            },
            // 显示搜索条件
            showSearch: true,
            // 遮罩层
            loading: false,
            pickerOptions: {
                shortcuts: [{
                    text: '最近一周',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                        picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '最近一个月',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                        picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '最近三个月',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                        picker.$emit('pick', [start, end]);
                    }
                }]
            },
        }
    },
    // 生命周期 - 创建完成（访问当前this实例）
    created() {
        this.getDeptTree();
        this.getDeptAndUsers();
        this.goalDate = [this.getNowFormatDate(), this.getNowFormatDate()]
    },
    // 生命周期 - 挂载完成（访问DOM元素）
    mounted() {

    },
    // methods方法
    methods: {
      /** 总计 */
      getSummaries(param) {
        const { columns, data } = param
        const sums = []
        columns.forEach((column, index) => {
          if (index === 0) {
            sums[index] = '总计';
            return;
          }
          const values = data.map(item => Number(item[column.property]));
          if (column.property !== 'nick_name' && column.property !== 'dept_name' && column.property !== 'avgCustCommentCount' && column.property !== 'commentRate') {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return prev + curr;
              } else {
                return prev;
              }
            }, 0);
            sums[index];
          }
        });
        return sums
      },
    getNowFormatDate() {
      var date = new Date();
      var seperator1 = "-";
      var year = date.getFullYear();
      var month = date.getMonth() + 1;
      var strDate = date.getDate();
      if (month >= 1 && month <= 9) {
        month = "0" + month;
      }
      if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
      }
      var currentdate = year + seperator1 + month + seperator1 + strDate;
      return currentdate;
    },
        /** 查询周目标管理列表 */
        getList() {
            this.loading = true;
            this.queryParams.params.queryType = this.queryType;

            this.addDateRange(this.queryParams, this.goalDate, "Time")

            getCustCommentStaticslist(this.queryParams).then(response => {
                this.userGoalList = response.rows;
                this.loading = false;
            });
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.form = {
                id: null,
                empId: null,
                orgId: null,
                visit: null,
                signed: null,
                addFriend: null,
                introduce: null,
                introduceVisit: null,
                introduceSigned: null,
                smsfollow: null,
                callTime: null,
                goalDate: null,
                createTime: null,
                updateTime: null
            };
            this.resetForm("form");
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            if (this.goalDate == null) {

                this.$message.error("请选择要查询得时间");
                return;
            }

            this.loading = true;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm("queryForm");
            this.handleQuery();
        },
        /** 查询部门归属下拉树结构 */
        getDeptTree() {
            var dept = { deptId: this.$store.state.user.deptid }
            childrenAlldeptTree(dept).then(response => {
                this.deptOptions = response.data;
            });
        },
        /** 获取部门归属和人员信息 */
        getDeptAndUsers() {
            getAllDeptandUsers().then((response) => {
                this.sysUsersList = response.data.sysUsersList;
            });
        },
        custleveldataDetails(ids) {
          //查询明细数据
          let inparams={};
          inparams.params={};
          inparams.params.ids=ids;
          inparams.pageNum=1;
          inparams.pageSize=10;
          this.$set(this.$data, 'form', inparams);
          this.open=true;
        },
    }
}
</script>
<style scoped>
/* @import url(); 引入css类 */
.report_span1 {
  color: blue;
  cursor: pointer;
}

.report_span2 {
  color: rgb(231, 62, 146);
  cursor: pointer;
}
</style>
